package com.louis.springboot.demo.filter;

import com.alibaba.fastjson.JSONObject;
import com.louis.springboot.demo.vo.HttpResult;
import org.springframework.core.annotation.Order;

import java.io.IOException;
import java.util.HashMap;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**

 * springboot 整合filter方式之一

 *

 * 以前web.xml配置：

 * <filter>

 *      <filter-name>FirstFilter</filter-name>

 *      <filter-class>com.zhong.spring_boot_filter_03.filter.FirstFilter</filter-class>

 * </filter>

 *

 * <filter-mapping>

 *       <filter-name>FirstFilter</filter-name>

 *       <url-pattern>/first</url-pattern>

 * </filter-mapping>

 *

 * FirstFilter

 */

//@Order(0)
@WebFilter(filterName = "FirstFilter",urlPatterns = {"/filter"})
//@WebFilter(urlPatterns = "/lvjia/carbodyad/api/*", filterName = "rest0PubFilter")
public class FirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       System.out.println(filterConfig);
    }

    @Override

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)

            throws IOException, ServletException {


       // System.out.println(response.getClass().toString());
        System.out.println("进入 FirstFilter ");
        System.out.println(request.getRemoteAddr());

        response.setContentType("application/json; charset=utf-8");
        HashMap<String, Object> data = new HashMap<>();
        data.put("my", "eeeeeee");
        HttpResult result = HttpResult.ok(data);
        String json = JSONObject.toJSONString(result);
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();

        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {
    }
}
